package com.amani.module.medical_supplies.biz;

import com.amani.module.medical_supplies.mapper.IWorkflowBiz;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricIdentityLink;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WorkflowBiz implements IWorkflowBiz {

    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IdentityService identityService;
    /*@Autowired
    private IUserService userService;*/
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;



    @Override
    public void claim(String taskId, String userId) {
        taskService.claim(taskId, userId);
    }

    @Override
    public void complete(String taskId) { taskService.complete(taskId); }

    @Override
    public void complete(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }

    @Override
    public void doCompleteTask(String taskId, String user, Map<String, Object> variables) {
        claim(taskId, user);
        complete(taskId, variables);
    }

    @Override
    public boolean isFinished(String processID) {
        //判断流程是否结束
        /**判断流程是否结束，查询正在执行的执行对象表*/
        boolean result = false;
        ProcessInstance rpi = runtimeService//
                .createProcessInstanceQuery()//创建流程实例查询对象
                .processInstanceId(processID)
                .singleResult();
        //说明流程实例结束了
        if (rpi == null) {
            /**查询历史，获取流程的相关信息*/
            HistoricProcessInstance hpi = historyService//
                    .createHistoricProcessInstanceQuery()//
                    .processInstanceId(processID)//使用流程实例ID查询
                    .singleResult();
            System.out.println(hpi.getId() + "    " + hpi.getStartTime() + "   " + hpi.getEndTime() + "   " + hpi.getDurationInMillis());
            result = true;
        }
        return result;
    }

    @Override
    public List<Task> queryTasksByRoleAndProcessID(String role, String processID) {
        return taskService.createTaskQuery()
                .taskCandidateGroup(role)
                .processInstanceId(processID)
                .list();
    }

    @Override
    public List<Task> queryTasksByCandidateUserAndProcessID(String user, String processID) {
        return taskService.createTaskQuery()
                .taskAssignee(user)
                .processInstanceId(processID)
                .list();
    }

    @Override
    public List<Task> queryTasksByCandidateUser(String user) {
        return taskService.createTaskQuery()
                .taskAssignee(user)
                .list();
    }

    @Override
    public Task queryTaskByRoleAndProcessID(String role, String processID) {
        return taskService.createTaskQuery()
                .taskCandidateGroup(role)
                .processInstanceId(processID)
                .singleResult();
    }


    @Override
    public List<Task> queryTodoListbyRole(String processDefinitionKey, List<String> roleNames) {
        List<Task> tasks = taskService
                .createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskCandidateGroupIn(roleNames)
                .orderByTaskCreateTime()
                .desc()
                .list();
        return tasks;
    }

/*    private int getDeptByUserId(int user) {
        LogisticalCenter center = userService.findUserLogisticalCenter(user);
        if (center != null) {
            return center.getId();
        }
        return -1;
    }*/


    public ProcessInstance startProcess(String processDefinitionKey, String bussinessKey, HashMap<String, Object> variables) {

        return runtimeService.startProcessInstanceByKey(processDefinitionKey, bussinessKey, variables);
    }

    @Override
    public Task searchTaskById(String taskID) {
        return taskService.createTaskQuery().taskId(taskID).singleResult();
    }

    @Override
    public ProcessInstance searchProcessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public String getBussinessKeyByProcessInstanceId(String processInstanceId) {
        ProcessInstance pi = searchProcessInstanceById(processInstanceId);
        String bussinessKey = "";
        if (pi != null) {
            bussinessKey = pi.getBusinessKey();//业务单号
        }
        return bussinessKey;
    }

    public String getHisBussinessKeyByProcessInstanceId(String processInstanceId) {
        HistoricProcessInstance h =  historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return h.getBusinessKey();
    }

    public  Map<String, Object> getProcessVariablesByTask(Task task) {
        Map<String, Object> variables = taskService.getVariables(task.getId());
        return variables;
    }

    public List<HistoricIdentityLink> findHistoryPersonTask(String processID) {
        List<HistoricIdentityLink> list = historyService.getHistoricIdentityLinksForProcessInstance(processID);
        if (list != null && list.size()>0) {
            for (HistoricIdentityLink historicIdentityLink : list) {
                System.out.println(historicIdentityLink.getTaskId()+" "
                        +historicIdentityLink.getType()+" "
                        +historicIdentityLink.getProcessInstanceId());
            }
        }
        return list;
    }

    public List<HistoricTaskInstance> queryHistoryListbyTaskAssignee(String processDefiniteKey,int userId) {
        List<HistoricTaskInstance> tasks = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(String.valueOf(userId))
                .processFinished()
                .processDefinitionKey(processDefiniteKey)
                .orderByTaskCreateTime()
                .desc().list();
        return tasks;
    }
    public List<HistoricTaskInstance> queryCurHistoryListbyTaskAssignee(String processDefiniteKey,int userId) {
        List<HistoricTaskInstance> tasks = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(String.valueOf(userId))
                .processDefinitionKey(processDefiniteKey)
                .orderByTaskCreateTime()
                .desc().list();
        return tasks;
    }


}

